package com.ht.pms.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ht.pms.core.common.exception.ServiceException;
import com.ht.pms.core.dao.SalaryEmailDao;
import com.ht.pms.core.dao.mapper.NoticeDingdingRecordMapper;
import com.ht.pms.core.dto.Result;
import com.ht.pms.core.dto.send.*;
import com.ht.pms.core.dto.dingding.MsgFeignDto;
import com.ht.pms.core.feign.MsgFeign;
import com.ht.pms.core.service.DingDingService;
import com.ht.pms.core.service.SalaryEmailService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DingDingServiceImpl extends ServiceImpl<NoticeDingdingRecordMapper, NoticeDingdingRecord> implements DingDingService {

    private static final Logger LOG = LoggerFactory.getLogger(SalaryEmailServiceImpl.class);

    @Autowired
    private NoticeDingdingRecordMapper noticeDingdingRecordMapper;

    @Autowired
    private SalaryEmailService salaryEmailService;

    @Autowired
    private MsgFeign msgFeign;
    @Autowired
    private SalaryEmailDao salaryEmailDao;

//    @Value("msg.dingding.tempid")
//    private String msgModelId;

    @Override
    public void sendDingdingMsg(SendSalaryReq dto) throws Exception {
        LOG.info("=============>>>>>>>>>发送钉钉开始");
        String batchCode = dto.getBatchCode();
        int flag = Integer.parseInt(dto.getFlag());
        int sendType = Integer.parseInt(dto.getSendType());
        int type = 2;
        List<String> jobCodes = null;
        List<PushMsgReq> noticeSendList =null;
        if (flag == 1) { //全部发送
            noticeSendList = noticeDingdingRecordMapper.findSendNoticeData(batchCode, sendType, jobCodes, 1,2); //state 为1 发送成功 sendServer 2 钉钉状态不为发送成功
        } else if (flag == 2) {
            if (dto.getSendBaseList() == null || dto.getSendBaseList().size() == 0) {
                throw new ServiceException("sendSalaryEmail", "缺少必要发送参数");
            } else {
                jobCodes = new ArrayList<>();
                List<SendBaseDto> sendParamList = dto.getSendBaseList();
                for (SendBaseDto sendBaseDto : sendParamList) {
                    jobCodes.add(sendBaseDto.getJobCode());
                }
                noticeSendList = noticeDingdingRecordMapper.findSendNoticeData(batchCode, sendType, jobCodes, 0,2); //state 0 未发送 为1 发送成功 sendServer 2 钉钉状态不为发送成功
                if(noticeSendList ==null){
                    throw new ServiceException("sendSalaryEmail", "请先进行发送");
                }
            }
        }
        //查询出所有需要发送的数据
//       noticeSendList = noticeDingdingRecordMapper.findSendNoticeData(batchCode, sendType, jobCodes, 1,2); //state 为1 发送成功 sendServer 2 钉钉状态不为发送成功
        String time = noticeDingdingRecordMapper.findSendTime(batchCode);
        String year = "";
        String month = "";
        if (!StringUtils.isBlank(time)) {
            String[] arr = time.split("-");
            year = arr[0];
            month = arr[1];
        }


        //组装钉钉的数据
        if (!CollectionUtils.isEmpty(noticeSendList)) {
            for (PushMsgReq dingDingMsgReq : noticeSendList) {
                MsgFeignDto msgFeignDto = new MsgFeignDto();
                Map<String, String> accessUrl = salaryEmailService.createAccessUrl(dingDingMsgReq.getJobCode(), batchCode, sendType, type);
                String url = "";
                String token = "";
                if (!MapUtils.isEmpty(accessUrl)) {
                    url = accessUrl.get("url");
                    token = accessUrl.get("token");
                }

                msgFeignDto.setKey2(url);
                msgFeignDto.setMsgTitle(sendType == 1 ? "考勤" : "工资");
                msgFeignDto.setMsgTo(dingDingMsgReq.getUserId());


                Map<String, String> map = new HashMap<>();
                map.put("year", year);
                map.put("month", month);
                map.put("title", msgFeignDto.getMsgTitle());
                msgFeignDto.setMsgBody(JSONObject.toJSON(map));
                System.out.println(msgFeignDto);
                Result result = msgFeign.sendRequest(msgFeignDto);
                LOG.info("===============>>>>>>>消息中心返回内容result=" + result);
//                Result result=Result.buildSuccess();
//                System.out.println(result);
                //记录发送状态  0 发送成功 1 发送失败 2 撤回
                int dstate = 0;
                int state = 0;
                if (result.getReturnCode() == 0) {
                    dstate = 1;
                    state = 0;
                    List<NoticeDingdingRecord> noticeList = noticeDingdingRecordMapper.selectList(new EntityWrapper<NoticeDingdingRecord>()
                            .eq("batch_code", batchCode).eq("job_code", dingDingMsgReq.getJobCode()).eq("send_type", sendType));
                    if (!CollectionUtils.isEmpty(noticeList)) {
                        for (NoticeDingdingRecord noticeDingdingRecord : noticeList) {
                            if(noticeDingdingRecord.getSendState() ==0 ){
                                noticeDingdingRecord.setSendState(2);
                                noticeDingdingRecordMapper.updateById(noticeDingdingRecord);
                            }

                        }
                    }
                } else {
                    dstate = 2;
                    state = 1;
                }


                noticeDingdingRecordMapper.updateDingDingState(batchCode, dingDingMsgReq.getJobCode(), dstate, sendType);

                NoticeDingdingRecord noticeRecordSend = new NoticeDingdingRecord();
                noticeRecordSend.setBatchCode(batchCode);
                noticeRecordSend.setJobCode(dingDingMsgReq.getJobCode());
                noticeRecordSend.setSendType(sendType);
                noticeRecordSend.setName(dingDingMsgReq.getName());
                noticeRecordSend.setSendState(state);
                noticeRecordSend.setSendCode(token);
                noticeRecordSend.setSendYm(time);
                noticeDingdingRecordMapper.insert(noticeRecordSend);
            }


            if (flag == 1) {
                NoticeSendDto noticeSendDto = new NoticeSendDto();
                noticeSendDto.setBatchCode(batchCode);
                noticeSendDto.setSendType(sendType);
                noticeSendDto.setSendServer(2); //钉钉
                salaryEmailDao.saveNoticeSendDto(noticeSendDto);
            }
        }

    }


    @Override
    public void sendRecall(int type, String jobCode, String batchCode, int sendType, List<Integer> sendServer) throws Exception {
        List<String> jobCodes = null;
        if (!StringUtils.isBlank(jobCode)) {
            jobCodes = new ArrayList<>();
            jobCodes.add(jobCode);
        }
        List<PushMsgReq> noticeSendList = noticeDingdingRecordMapper.findSendNoticeData(batchCode, sendType, jobCodes, 3,3); //不为撤回 sendServer 邮件和钉钉查询
        if (!CollectionUtils.isEmpty(noticeSendList)) {

            if (!CollectionUtils.isEmpty(sendServer)) {
                if (sendServer.size() == 2) {
                    //撤回邮件数据
                    noticeDingdingRecordMapper.updateState(  batchCode, jobCodes,   3,  sendType,  1); //更新邮件数据状态
                    noticeDingdingRecordMapper.updateRecordState(batchCode, jobCodes,2,1); //邮件
                    //撤回钉钉数据
                    noticeDingdingRecordMapper.updateState(  batchCode, jobCodes,   3,  sendType,  2); //更新钉钉数据状态
                    noticeDingdingRecordMapper.updateRecordState(batchCode, jobCodes,2,2); //钉钉
                } else if (sendServer.size() == 1) {
                    if (sendServer.get(0).equals(1)) { //撤回邮件
                        noticeDingdingRecordMapper.updateState(  batchCode, jobCodes,   3,  sendType,  1); //更新邮件数据状态
                        noticeDingdingRecordMapper.updateRecordState(batchCode, jobCodes,2,1); //邮件
                    } else if (sendServer.get(0).equals(2)) { //发送钉钉
                        noticeDingdingRecordMapper.updateState(  batchCode, jobCodes,   3,  sendType,  2); //更新钉钉数据状态
                        noticeDingdingRecordMapper.updateRecordState(batchCode, jobCodes,2,2); //钉钉
                    }
                }
            }
        } else {
            throw new ServiceException("sendRecall", "没有需要撤回的数据");
        }
    }
}
